package com.haruhi.bot.endpoint.ws.server;

import com.haruhi.bot.endpoint.ws.model.MessageBox;
import com.haruhi.bot.endpoint.ws.MessageQueue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class ServerEndpoint extends TextWebSocketHandler {

    private final String path;

    public ServerEndpoint(String path){
        this.path = path;
        SERVER_ENDPOINT_MAP.put(path,this);
    }

    // 一个路径对应一个服务终端
    private static final Map<String,ServerEndpoint> SERVER_ENDPOINT_MAP = new ConcurrentHashMap<>();

    public static ServerEndpoint getServerEndpoint(String path){
        return SERVER_ENDPOINT_MAP.get(path);
    }
    // 一个session对应一个服务终端
    private static final Map<WebSocketSession,ServerEndpoint> SESSION_SERVER_ENDPOINT_CONTAINER = new ConcurrentHashMap<>();
    public static Map<WebSocketSession,ServerEndpoint> getSessionServerContainer(){
        return SESSION_SERVER_ENDPOINT_CONTAINER;
    }
    public static Long getBotIdBySession(WebSocketSession session){
        return SESSION_SERVER_ENDPOINT_CONTAINER.get(session).getSessionBotIdContainer().get(session);
    }

    // 一个session对应一个机器人qq号 该map的size就是一个终端的连接数
    private final Map<WebSocketSession,Long> sessionBotIdContainer = new ConcurrentHashMap<>();
    public Map<WebSocketSession,Long> getSessionBotIdContainer(){
        return this.sessionBotIdContainer;
    }


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        getSessionServerContainer().put(session,this);
        getSessionBotIdContainer().put(session,0L);
        log.info("[{}]连接成功：{}",this.path, session.getRemoteAddress());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        log.info("[{}] [{}]收到消息：{}",session.getId(),this.path,payload);
        MessageQueue.offer(new MessageBox(session,this,payload));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        getSessionServerContainer().remove(session);
        getSessionBotIdContainer().remove(session);
        log.info("[{}]连接异常",this.path,exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        getSessionServerContainer().remove(session);
        getSessionBotIdContainer().remove(session);
        log.info("[{}]连接断开",this.path);
    }
}
